//
//  YWDetectAndUpkeepManager.m
//  maintain
//
//  Created by Kyo on 16/9/6.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWDetectAndUpkeepManager.h"
#import "WMHttpTool.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "MJExtension.h"
#import "NSDate+Additions.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import <Bugly/Bugly.h>

#import "YWDBTool.h"
#import "YWMissionManager.h"
#import "YWDetectAndUpkeepDBManager.h"
#import "YWResourceManager.h"
#import "YWLogRecordTool.h"
#import "YWEwinManager.h"

#import "YWEquipmentType.h"
#import "YWEquipmentFieldRecord.h"

static BOOL isUploading = NO;

@interface YWDetectAndUpkeepManager ()
@property (nonatomic, strong) dispatch_group_t group;
//@property (nonatomic, strong) dispatch_queue_t serialQueue;
//@property (nonatomic, strong) dispatch_semaphore_t signal;
@end

@implementation YWDetectAndUpkeepManager
//YWSingletonM(Manager)

- (dispatch_group_t)group{
    if (!_group) {
        _group = dispatch_group_create();
    }
    return _group;
}

//- (dispatch_queue_t)serialQueue{
//    if (!_serialQueue) {
//        _serialQueue = dispatch_queue_create("uploadDetectAndUpkeepRecordserialQueue", DISPATCH_QUEUE_SERIAL); //创建上传串行队列
//    }
//    return _serialQueue;
//}
//
//- (dispatch_semaphore_t)signal{
//    if (!_signal) {
//        _signal = dispatch_semaphore_create(1);
//    }
//    return _signal;
//}

+ (BOOL)updateDetectAndUpkeepMissionWithArray:(NSArray*)missions{
    return [YWDetectAndUpkeepDBManager updateDetectAndUpkeepMissionWithArray:missions];
}

+ (NSArray*)detectAndUpkeepMissionWithStatus:(YWMissionFinishStatus)status maintenanceType:(YWMaintenanceType)type page:(NSInteger)page{
    return [YWDetectAndUpkeepDBManager detectAndUpkeepMissionWithStatus:status maintenanceType:type page:page];
}

+ (YWMaintenanceMission *)maintenanceMissionWithMissionId:(NSInteger)missionId{
    return [YWDetectAndUpkeepDBManager maintenanceMissionWithMissionId:missionId];
}

+ (BOOL)updateMaintenanceRecordJsons:(NSArray*)maintenanceRecordJsons maintenanceTypeId:(YWMaintenanceType)maintenanceTypeId
{
    if (!maintenanceRecordJsons.count) {
        return NO;
    }
    BOOL result = NO;
    switch (maintenanceTypeId) {
        case YWMaintenanceTypeDetection:
            result = [[YWDBTool shareDBTool] saveEquipmentDetectionRecordWithJsonArray:maintenanceRecordJsons];
            break;
        case YWMaintenanceTypeUpkeep:
            result = [[YWDBTool shareDBTool] saveEquipmentUpkeepRecordWithJsonArray:maintenanceRecordJsons];
            break;
        default:
            break;
    }
    return result;
}

+ (BOOL)updateMaintenanceRecords:(NSArray*)maintenanceRecords maintenanceTypeId:(YWMaintenanceType)maintenanceTypeId
{
    if (!maintenanceRecords.count) {
        return NO;
    }
    BOOL result = NO;
    switch (maintenanceTypeId) {
        case YWMaintenanceTypeDetection:
            result = [[YWDBTool shareDBTool] updateEquipmentDetectionRecordWithArray:maintenanceRecords];
            break;
        case YWMaintenanceTypeUpkeep:
            result = [[YWDBTool shareDBTool] updateEquipmentUpkeepRecordWithArray:maintenanceRecords];
            break;
        default:
            break;
    }
    return result;
}

+ (NSArray*)maintenanceRecordArrayWithEquipmentId:(NSString*)equipmentId maintenanceTypeId:(YWMaintenanceType)maintenanceTypeId withPage:(NSInteger)page{
    NSArray* maintenanceRecords = nil;
    switch (maintenanceTypeId) {
        case YWMaintenanceTypePatrol:
            //        maintenanceRecords = [[YWDBTool shareDBTool] patrolRecordsWithEquipmentId:equipmentId];
            break;
        case YWMaintenanceTypeDetection:
            maintenanceRecords = [[YWDBTool shareDBTool] detectionRecordArrayWithEquipmentId:equipmentId withPage:page];
            break;
        case YWMaintenanceTypeUpkeep:
            maintenanceRecords = [[YWDBTool shareDBTool] upkeepRecordArrayWithEquipmentId:equipmentId withPage:page];
            break;
        default:
            break;
    }
    return maintenanceRecords;
}

+ (YWEquipmentMaintenanceRecord *)maintenanceRecordWithMission:(YWMaintenanceMission *)mission equipmentId:(NSString *)equipmentId{
    YWEquipmentMaintenanceRecord* maintenanceRecord = nil;
    switch (mission.maintenanceTypeId) {
        case YWMaintenanceTypeDetection:
            maintenanceRecord = [[YWDBTool shareDBTool] detectionRecordsWithMissionId:mission.missionId equipmentId:equipmentId];
            break;
        case YWMaintenanceTypeUpkeep:
            maintenanceRecord = [[YWDBTool shareDBTool] upkeepRecordsWithMissionId:mission.missionId equipmentId:equipmentId];
            break;
        default:
            break;
    }
    return maintenanceRecord;
}

+ (NSDictionary *)detectAndUpkeepRecordsWithMission:(YWMaintenanceMission *)mission{
    return [[YWDBTool shareDBTool] detectAndUpkeepRecordsWithMission:mission];
}

+ (NSString *)missionCycleStringWithCycle:(NSInteger)missionCycle{
    NSString *cycleName = NSLocalizedString(@"none", nil);
    switch (missionCycle) {
        case YWMissionCycleNull:
            cycleName = NSLocalizedString(@"noCycle", nil);//@"不循环";
            break;
        case YWMissionCycleYear:
            cycleName = NSLocalizedString(@"cycleYear", nil);//@"年度";
            break;
        case YWMissionCycleHalfYear:
            cycleName = NSLocalizedString(@"cycleHalfYear", nil);//@"半年";
            break;
        case YWMissionCycleQuarter:
            cycleName = NSLocalizedString(@"cycleQuarter", nil);//@"季度";
            break;
        case YWMissionCycleMonth:
            cycleName = NSLocalizedString(@"cycleMonth", nil);//@"每月";
            break;
        case YWMissionCycleWeek:
            cycleName = NSLocalizedString(@"cycleWeek", nil);//@"每周";
            break;
        case YWMissionCycleDay:
            cycleName = NSLocalizedString(@"cycleDay", nil);//@"每日";
            break;
            
        default:
            break;
    }
    return cycleName;
}

//请求维保任务
+ (void)requestDetectAndUpKeepMissionWithUrl:(NSString *)url page:(NSInteger)page pageSize:(NSInteger)pageSize status:(NSInteger)status completeBlock:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (status == YWMissionFinishStatusUnfinished) {
        [params setValue:@(status) forKey:@"missionStatus"];
    }else{
        NSString * getStatus = [NSString stringWithFormat:@"%ld,%ld",(unsigned long)YWMissionStatusFinished,(unsigned long)YWMissionStatusExpire];
        [params setValue:getStatus forKey:@"missionStatusList"];
    }
//    [params setValue:@(status) forKey:@"missionStatus"];
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }
    YWLog(@"%@",params);
    
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* missions = [YWMaintenanceMission mj_objectArrayWithKeyValuesArray:json];
        [YWDetectAndUpkeepManager updateDetectAndUpkeepMissionWithArray:missions];
        if (complete) {
            complete(missions.count);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(0);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
//请求单个维保任务(检测保养)
+ (void)requestMissionWithMissionId:(NSInteger)missionId completeBlock:(void (^)(YWMaintenanceMission*mission))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(nil);}return;}
    
    NSString* url = [NSString stringWithFormat:@"%@/%ld", [YWCommonTool getAllMissionUrl], (long)missionId];
    [[WMHttpTool shareHttpTool] getWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        YWMaintenanceMission* mission = [YWMaintenanceMission mj_objectWithKeyValues:json];
        if (mission) {
            [YWDetectAndUpkeepManager updateDetectAndUpkeepMissionWithArray:@[mission]];
        }
        
        if (complete) {
            complete(mission);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(nil);
            if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
            }
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

+ (void)requestMissionRecordWithMission:(YWMaintenanceMission*)mission completeBlock:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    
    NSString* url = [NSString stringWithFormat:@"%@/%ld", [YWCommonTool getMissionRecordUrl], (long)mission.missionId];
    YWLog(@"%@",url);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        NSArray* maintenanceRecordJsons = [YWEquipmentMaintenanceRecordJson mj_objectArrayWithKeyValuesArray:json];
        //保存维保记录
        [YWDetectAndUpkeepManager updateMaintenanceRecordJsons:maintenanceRecordJsons maintenanceTypeId:mission.maintenanceTypeId];
        if (maintenanceRecordJsons.count) {
            NSMutableArray *fieldRecorsArray = [NSMutableArray array];
            [maintenanceRecordJsons enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecordJson*  _Nonnull recordJson, NSUInteger idx, BOOL * _Nonnull stop) {
                [recordJson.equipmentFields enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord*  _Nonnull fieldRecord, NSUInteger idx, BOOL * _Nonnull stop) {
                    fieldRecord.uniqueTag = recordJson.uniqueTag;
                    fieldRecord.maintenanceTypeId = mission.maintenanceTypeId;
                    [fieldRecorsArray addObject:fieldRecord];
                }];
            }];
            //保存参数记录
            [[YWMissionManager shareManager] updateEquipmentFieldRecords:fieldRecorsArray];
            if (complete) {
                complete(maintenanceRecordJsons.count);
            }
        }
        
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(0);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}


+ (void)requestAssignMissionCountWithBuildingId:(NSString*)buildingId equipmentTypeId:(NSInteger)equipmentTypeId maintenanceTypeId:(NSInteger)maintenanceTypeId WithComplete:(void(^)(YWAssignMissionCount* assignMissionCount))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(nil);}return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:buildingId?:@"" forKey:@"buildingId"];
    [params setValue:@(equipmentTypeId) forKey:@"equipmentTypeId"];
    [params setValue:@(maintenanceTypeId) forKey:@"maintenanceTypeId"];
    [params setValue:@([NSDate date].month) forKey:@"theMonth"];
    [params setValue:@([NSDate date].year) forKey:@"theYear"];
    YWLog(@"%@",params);
    [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool getAssignMissionCountUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        YWAssignMissionCount* assignMissionCountModel = [YWAssignMissionCount mj_objectWithKeyValues:json];
        
        if (complete) {
            complete(assignMissionCountModel);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(nil);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

+ (void)assiginDetectAndUpkeepMission:(NSDictionary *)params WithComplete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    [[WMHttpTool shareHttpTool] postWithUrl:[YWCommonTool getAllMissionUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        YWMaintenanceMission* mission = [YWMaintenanceMission mj_objectWithKeyValues:json];
        if (mission) {
            mission.missionStatus = YWMissionStatusUnfinished;
            [YWDetectAndUpkeepDBManager updateDetectAndUpkeepMissionWithArray:@[mission]];
            [YWDetectAndUpkeepManager requestMissionWithMissionId:mission.missionId completeBlock:^(YWMaintenanceMission *mission) {
                [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshPostAssignDetectAndUpkeepMissionNotification object:nil];
            }];
            NSInteger maintenanceTypeId = [[params objectForKey:@"maintenanceTypeId"] integerValue];
            if (maintenanceTypeId == YWUnReadCountTypeUpkeep) {
                [[YWEwinManager shareManager] addTotalCountWithType:YWUnReadCountTypeUpkeep];
            }else if (maintenanceTypeId == YWUnReadCountTypeDetection){
                [[YWEwinManager shareManager] addTotalCountWithType:YWUnReadCountTypeDetection];
            }
        }
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"kTextAssignFailed", nil)];
        }
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

+ (void)requestDeleteMission:(NSInteger)missionId maintenanceType:(NSInteger)typeId completeBlock:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    NSString *url = [NSString stringWithFormat:@"%@/%ld",[YWCommonTool getAllMissionUrl],(long)missionId];
    [[WMHttpTool shareHttpTool] deleteWithUrl:url params:nil success:^(NSHTTPURLResponse* response, id json) {
        BOOL success = [[YWDBTool shareDBTool] mofifyMissionStatusWithMissionId:missionId maintenanceType:typeId];
        if (success) {
            [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshDeleteDetectAndUpkeepMissionNotification object:nil];
        }
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

+ (void)requestModifyDetectAndUpkeepMission:(NSDictionary *)params complete:(void (^)(BOOL))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(NO);}return;}
    
    [[WMHttpTool shareHttpTool] putWithUrl:[YWCommonTool getAllMissionUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(NO);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"modifyFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

+ (NSString *)allUnfinishDetectAndUpkeepMissionIds{
    return [YWDetectAndUpkeepDBManager allUnfinishDetectAndUpkeepMissionIds];
}

+ (void)updateDetectAndUpkeepMissionStatus{
    /**
     *  去除那些删除的任务
     */
    NSString* missionIdString = [self allUnfinishDetectAndUpkeepMissionIds];
    // YWLog(@"%@", missionString);
    if (missionIdString.length) {
        NSDictionary *dic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
        [WMHttpTool shareHttpTool].HTTPHeaders = dic;
        if (dic == nil) {return;}
        [[WMHttpTool shareHttpTool] getWithUrl:[YWCommonTool getMissionStatusUrl] params:@{ @"missionIds" : missionIdString ?: @"" } success:^(NSHTTPURLResponse* response, id json) {
            NSArray* missionStatusJsons = [YWMissionStatusJson mj_objectArrayWithKeyValuesArray:json];
            YWLoginUser *currentUser = [YWLoginTool loginUser];
            [missionStatusJsons enumerateObjectsUsingBlock:^(YWMissionStatusJson*  _Nonnull missionStatusJson, NSUInteger idx, BOOL * _Nonnull stop) {
                //判断这个任务执行人有没有被删除
                if (missionStatusJson.status == -1 || ((![YWCommonTool containSelfInHandlers:missionStatusJson.executors]) && missionStatusJson.creator.uniqueId != currentUser.uniqueId)) {
                    //修改任务为删除状态
                    YWMaintenanceMission *mission = [self maintenanceMissionWithMissionId:missionStatusJson.missionId];
                    if (![mission.observerIds containsString:@(currentUser.uniqueId).stringValue]) {
                        [[YWMissionManager shareManager] mofifyMissionStatusWithMissionId:missionStatusJson.missionId maintenanceType:missionStatusJson.maintenanceTypeId];
                    }
                }
//                else{
//                    //完成
//                    mission.creator = missionStatusJson.creator;
//                    mission.executors = missionStatusJson.executors;
//                    mission.executorIds = [YWCommonTool handlerIdsWithHandlerArray:missionStatusJson.executors];
//                    if (missionStatusJson.equipmentQuantity!=0 && missionStatusJson.completedQuantity !=0 && missionStatusJson.equipmentQuantity <= missionStatusJson.completedQuantity) {
//                        mission.missionStatus = YWMissionStatusFinished;
//                        mission.finishTime = [[NSDate date] timeIntervalSince1970] * 1000;
//                        mission.completedQuantity = missionStatusJson.completedQuantity;
//                    }
//                    [YWDetectAndUpkeepManager updateDetectAndUpkeepMissionWithArray:mission?@[ mission ]:nil];
//                }
            }];
        } failure:^(NSHTTPURLResponse* response, NSError* error) {
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        }];
    }
}

+ (void)requestEquipmentDetectAndUpkeepRecordWithMaintenanceTypeId:(NSInteger)maintenanceTypeId equipmentIds:(NSString *)equipmentIds page:(NSInteger)page pageSize:(NSInteger)pageSize completeBlock:(void (^)(NSInteger))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(0);}return;}
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    [params setObject:equipmentIds forKey:@"equipmentIds"];
    [params setObject:@(maintenanceTypeId) forKey:@"maintenanceTypeId"];
    if (page) {
        [params setObject:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setObject:@(pageSize) forKey:@"pageSize"];
    }
    NSString *url = [YWCommonTool getEquipmentDetectAndUpkeepRecordUrl];
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* maintenanceRecordJsons = [YWEquipmentMaintenanceRecordJson mj_objectArrayWithKeyValuesArray:json];
        
        if (maintenanceRecordJsons.count) {
            NSMutableArray* fieldRecorsArray = [NSMutableArray array];
            [maintenanceRecordJsons enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecordJson* _Nonnull recordJson, NSUInteger idx, BOOL* _Nonnull stop) {
                [recordJson.equipmentFields enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord* _Nonnull fieldRecord, NSUInteger idx, BOOL* _Nonnull stop) {
                    fieldRecord.uniqueTag = recordJson.uniqueTag;
                    fieldRecord.maintenanceTypeId = maintenanceTypeId;
                    [fieldRecorsArray addObject:fieldRecord];
                }];
                [recordJson.pictures enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger idx, BOOL* _Nonnull stop) {
                    picture.missionId = recordJson.missionId;
                    picture.recordId = recordJson.recordId;
                    picture.maintenanceType = recordJson.maintenanceTypeId;
                    picture.equipmentId = recordJson.equipmentId;
                }];
            }];
            [YWDetectAndUpkeepManager updateMaintenanceRecordJsons:maintenanceRecordJsons maintenanceTypeId:maintenanceTypeId];
            [[YWMissionManager shareManager] updateEquipmentFieldRecords:fieldRecorsArray];
        }
        
        if (complete) {
            complete(maintenanceRecordJsons.count);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(0);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }
        YWLog(@"%@,%@",url,params);
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)startUploadDetectAndUpkeepRecords:(NSArray *)records maintenanceMission:(YWMaintenanceMission *)maintenanceMission pictures:(NSArray *)pictures{
    if (records.count==0 || maintenanceMission==nil) {
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_group_enter(self.group);
        if (pictures.count >0) {
            [[YWResourceManager shareManager] uploadLocalPictureToAliyunOSS:pictures isAvatar:NO complete:^(BOOL isError, NSArray* uploadPictures) {
                [self pictureCompleteHandleWithRecords:records maintenanceMission:maintenanceMission uploadPictures:uploadPictures error:isError];
            }];
        }else{
            [self pictureCompleteHandleWithRecords:records maintenanceMission:maintenanceMission uploadPictures:nil error:NO];
        }
        dispatch_group_wait(self.group, DISPATCH_TIME_FOREVER);
    });
}

- (void)pictureCompleteHandleWithRecords:(NSArray*)records maintenanceMission:(YWMaintenanceMission *)maintenanceMission uploadPictures:(NSArray*)uploadPictures error:(BOOL)isError{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[YWResourceManager shareManager] savePicturesToDBWithArray:uploadPictures];
        if (!isError) {
            //提交
            [self submitMaintenanceMissionRequestWithRecords:records Mission:maintenanceMission];
        }else {
            [records enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord* _Nonnull maintenanceRecord, NSUInteger idx, BOOL* _Nonnull stop) {
                //更新记录状态为失败
                [[YWMissionManager shareManager] updateMissionMaintenceRecordUploadStatus:YWEquipmentMaintenanceRecordUploadStatusUnFinished recordId:maintenanceRecord.recordId maintenanceTypeId:maintenanceMission.maintenanceTypeId];
            }];
            maintenanceMission.uploadFail = YES;
            [[YWMissionManager shareManager] setUploadFailWithMission:maintenanceMission];
            dispatch_group_leave(self.group);
        }
    });
}

//----------提交检测，保养记录
- (void)submitMaintenanceMissionRequestWithRecords:(NSArray*)maintenanceRecords Mission:(YWMaintenanceMission*)mission{
    NSDictionary *headers = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headers;
    if (headers == nil) {dispatch_group_leave(self.group);return;}
    
    NSMutableDictionary* params = [NSMutableDictionary dictionary];
    if (mission.missionId > 0) {
        [params setObject:@(mission.missionId) forKey:@"missionId"];
    }
    [params setObject:@(mission.maintenanceTypeId) forKey:@"typeId"];
    
    [maintenanceRecords enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord* _Nonnull maintenanceRecord, NSUInteger idx, BOOL* _Nonnull stop) {
        NSArray* pictures = [[YWMissionManager shareManager] picturesWithRecordId:maintenanceRecord.recordId maintenanceType:mission.maintenanceTypeId];
        [pictures enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger pictureIdx, BOOL* _Nonnull stop) {
            [params setObject:picture.bigPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].url", (unsigned long)idx, (unsigned long)pictureIdx]];
            [params setObject:picture.smallPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].thumbnailUrl", (unsigned long)idx, (unsigned long)pictureIdx]];
            [params setObject:picture.smallPictureUrl ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].pictures[%lu].previewUrl", (unsigned long)idx, (unsigned long)pictureIdx]];
        }];
        [params setObject:maintenanceRecord.equipmentId ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].equipment.equipmentId", (unsigned long)idx]];
        [params setObject:maintenanceRecord.note ?: @"" forKey:[NSString stringWithFormat:@"records[%lu].note", (unsigned long)idx]];
        [params setObject:@(maintenanceRecord.status) forKey:[NSString stringWithFormat:@"records[%lu].statusTypeId", (unsigned long)idx]];
        //临时任务增加uniqueTag,这里就用时间戳字符串来做
        NSString *uniqueTag = maintenanceRecord.uniqueTag?:[YWCommonTool randStringId];
        [params setObject:uniqueTag forKey:[NSString stringWithFormat:@"records[%lu].uniqueTag", (unsigned long)idx]];
        //自定义属性
        [maintenanceRecord.equipmentFieldRecord enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord*  _Nonnull fieldRecord, NSUInteger cusIdx, BOOL * _Nonnull stop) {
            if (fieldRecord.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
                [params setObject:@(fieldRecord.fieldId) forKey:[NSString stringWithFormat:@"records[%lu].equipmentFields[%lu].fieldId", (unsigned long)idx, (unsigned long)cusIdx]];
                [params setObject:@(fieldRecord.fieldOption.fieldOptionId) forKey:[NSString stringWithFormat:@"records[%lu].equipmentFields[%lu].fieldValue", (unsigned long)idx, (unsigned long)cusIdx]];
            }else{
                if (fieldRecord.fieldValue.length>0) {
                    [params setObject:@(fieldRecord.fieldId) forKey:[NSString stringWithFormat:@"records[%lu].equipmentFields[%lu].fieldId", (unsigned long)idx, (unsigned long)cusIdx]];
                    [params setObject:fieldRecord.fieldValue?:@"" forKey:[NSString stringWithFormat:@"records[%lu].equipmentFields[%lu].fieldValue", (unsigned long)idx, (unsigned long)cusIdx]];
                }
            }
        }];
        long long executeTime = [YWCommonTool numberWithTime:maintenanceRecord.completeTime];
        [params setObject:@(executeTime) forKey:[NSString stringWithFormat:@"records[%lu].clientExecuteTime", (unsigned long)idx]];
        long long nowTime = [YWCommonTool numberWithTime:[[NSDate date] timeIntervalSince1970]*1000];
        [params setObject:@(nowTime) forKey:[NSString stringWithFormat:@"records[%lu].clientCurrentTime", (unsigned long)idx]];
        long long scanTime = [YWCommonTool numberWithTime:maintenanceRecord.clientScanTime];
        scanTime = scanTime<0?0:scanTime;
        [params setObject:@(scanTime) forKey:[NSString stringWithFormat:@"records[%lu].clientScanTime", (unsigned long)idx]];
    }];
    NSString *url = [YWCommonTool getSubmitMissionUrl];
    YWLog(@"url -- %@,%@",url,params);
    //保存请求前的参数日志
    NSString *logTag = [YWCommonTool randStringId];
    NSMutableDictionary * logDic = [[YWLogRecordTool shareLogRecordManager] getLogDictionaryWithModule:@"检测保养" interface:url params:params headers:headers tag:logTag];
    [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:logDic];
    
    [[WMHttpTool shareHttpTool] postWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWLog(@"mission upload success");
            [maintenanceRecords enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord* _Nonnull maintenanceRecord, NSUInteger idx, BOOL* _Nonnull stop) {
                [[YWMissionManager shareManager] updateMissionMaintenceRecordUploadStatus:YWEquipmentMaintenanceRecordUploadStatusFinished recordId:maintenanceRecord.recordId maintenanceTypeId:mission.maintenanceTypeId];
            }];
            if (mission.maintenanceTypeId==YWMaintenanceTypeDetection) {
                [[YWEwinManager shareManager] subtractTotalCountWithType:YWUnReadCountTypeDetection];
            }else{
                [[YWEwinManager shareManager] subtractTotalCountWithType:YWUnReadCountTypeUpkeep];
            }
            if (mission.uploadFail) {
                NSArray* unUploadRecord = [[YWDBTool shareDBTool] finishedUnUploadMaintenanceRecordWithMission:mission];
                if (unUploadRecord.count == 0) {
                    mission.uploadFail = NO;
                    [[YWMissionManager shareManager] setUploadFailWithMission:mission];
                }
            }
            //保存请求成功的参数日志
            NSMutableDictionary * successDic =
            [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:@"无" logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:successDic];
            
            dispatch_group_leave(self.group);
        });
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
            //保存请求失败的参数日志
            NSString * result = [NSString stringWithFormat:@"%s,error:%@", __func__, error.localizedDescription];
            NSMutableDictionary * failedDic = [[YWLogRecordTool shareLogRecordManager] successOrFailedLogDicWith:logDic statusCode:response.statusCode errorInfo:result logTag:logTag];
            [[YWLogRecordTool shareLogRecordManager] saveLocalPatameterLog:failedDic];
            //上传错误参数
            if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
                NSString *statusCode = [NSString stringWithFormat:@"statusCode: %@",@(response.statusCode).stringValue];
                [Bugly reportException:[NSException exceptionWithName:@"检测保养接口错误" reason:statusCode userInfo:params]];
            }
            
            [maintenanceRecords enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord* _Nonnull maintenanceRecord, NSUInteger idx, BOOL* _Nonnull stop) {
                //更新上传状态
                [[YWMissionManager shareManager] updateMissionMaintenceRecordUploadStatus:YWEquipmentMaintenanceRecordUploadStatusUnFinished recordId:maintenanceRecord.recordId maintenanceTypeId:mission.maintenanceTypeId];
            }];
            
            mission.uploadFail = YES;
            [[YWMissionManager shareManager] setUploadFailWithMission:mission];
            
            dispatch_group_leave(self.group);
        });
    }];
}

- (void)uploadFailedDetectAndUpkeepRecords{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (![YWLoginTool isLogin]) {
            return;
        }
        if (isUploading == YES) {
            return;
        }
        isUploading = YES;
        
        //失败的任务
        NSArray* detectAndUpkeepMission = [[YWDBTool shareDBTool] uploadFailDetectAndUpkeepMission];
        [detectAndUpkeepMission enumerateObjectsUsingBlock:^(YWMaintenanceMission* _Nonnull maintenanceMission, NSUInteger idx, BOOL* _Nonnull stop) {
            //失败的记录
            NSArray *uploadRecords = [[YWDBTool shareDBTool] finishedUnUploadMaintenanceRecordWithMission:maintenanceMission];
            //图片
            NSArray* pictures = [[YWDBTool shareDBTool] picturesWithMissionId:maintenanceMission.missionId maintenanceType:maintenanceMission.maintenanceTypeId];
            dispatch_group_enter(self.group);
            if (uploadRecords.count >0) {
                if (pictures.count >0) {
                    [[YWResourceManager shareManager] uploadLocalPictureToAliyunOSS:pictures isAvatar:NO complete:^(BOOL isError, NSArray* uploadPictures) {
                        [self pictureCompleteHandleWithRecords:uploadRecords  maintenanceMission:maintenanceMission uploadPictures:uploadPictures error:isError];
                    }];
                }else{
                    [self pictureCompleteHandleWithRecords:uploadRecords  maintenanceMission:maintenanceMission uploadPictures:nil error:NO];
                }
                dispatch_group_wait(self.group, DISPATCH_TIME_FOREVER);
            }
            
            if (idx == detectAndUpkeepMission.count-1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPushBackgroundUploadRecordSuccessNotification object:nil];
                });
            }
        }];
        isUploading = NO;
    });
}


@end
